package com.spzx.product.helper;

import com.spzx.product.api.domain.CategoryVo;
import org.aspectj.weaver.ast.Var;

import java.util.ArrayList;
import java.util.List;

/**
 * ClassName: CategoryHelper
 * Package: com.spzx.product.helper
 * Description:
 *
 * @Author ycy
 * @Create 2024/8/9 19:47
 * @Version 1.0
 */
public class CategoryHelper {
    /**
     * 使用递归方法建树
     */
    public static List<CategoryVo> buildTree(List<CategoryVo> categoryVoList){
        List<CategoryVo> trees = new ArrayList<>();


        for (CategoryVo categoryVo : categoryVoList){
            if (categoryVo.getParentId().longValue() == 0){
                trees.add(findChildren(categoryVo,categoryVoList));

            }
        }
        return trees;
    }

    /**
     * 递归查找子节点
     */
    public static CategoryVo findChildren(CategoryVo categoryVo,List<CategoryVo> treeNodes){
        categoryVo.setChildren(new ArrayList<CategoryVo>());

        for (CategoryVo treeNode : treeNodes) {
            if (categoryVo.getId().longValue() == treeNode.getParentId().longValue()){
                if (categoryVo.getChildren() == null){
                    categoryVo.setChildren(new ArrayList<>());
                }
                categoryVo.getChildren().add(findChildren(treeNode,treeNodes));
            }
        }
        return categoryVo;
    }
}
